package com.projectsquirrel;

import java.io.OutputStreamWriter;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Address;
import android.location.Geocoder;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;

import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class newObservation extends Activity implements LocationListener {
	private LocationManager myManager;
	private double latitude = 0;
	private double longitude = 0;
	private boolean gpsDisabled = false;
	private AlertDialog.Builder builder;
	AlertDialog gpsAlert;
	private TextView displayTime;
	private TextView displayDate;
	private TextView displayDate2;
	private TextView zipcodeEmg;
	private Observation newObs;
	private EditText zipCodeText;
	private int mHour = 1;
    private int mMinute = 1;
    private int mYear = 2000;
    private int mMonth = 1;
    private int mDay = 1;
    private Geocoder geocoder; 
    static final int TIME_DIALOG_ID = 999990099;
    static final int DATE_DIALOG_ID = 999990098;
    private String zipCode;
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.observationform);
	    final String TAG = "Project_2_Group_6";
	    ImageButton infoIconButton = (ImageButton) findViewById(R.id.infoScreenIcon);
	    final FrameLayout layout1a = (FrameLayout) findViewById(R.id.frameLayout1a);
	    final FrameLayout layout1 = (FrameLayout) findViewById(R.id.frameLayout1);
	    final FrameLayout layout2 = (FrameLayout) findViewById(R.id.frameLayout2);
	    final FrameLayout layout3 = (FrameLayout) findViewById(R.id.frameLayout3);
	    final FrameLayout layout4 = (FrameLayout) findViewById(R.id.confirmationLayout);
	    final Button nextObsButton1 = (Button) findViewById(R.id.nextObsScreen1);
	    final Button nextObsButton2 = (Button) findViewById(R.id.nextObsScreen2);
	    final Button nextObsButton3 = (Button) findViewById(R.id.nextObsScreen3);
	    final Button ObsSubmitButton = (Button) findViewById(R.id.ObsSubmit);
	    final Button backObsButton1a = (Button) findViewById(R.id.backObsScreen1a);
	    final Button backObsButton1 = (Button) findViewById(R.id.backObsScreen1);
	    final Button backObsButton2 = (Button) findViewById(R.id.backObsScreen2);
	    zipcodeEmg = (TextView) findViewById(R.id.zipcodeLabel);
	    zipCodeText = (EditText) findViewById(R.id.ZipCodeText);
	    zipCodeText.setVisibility(View.GONE);
	    zipcodeEmg.setVisibility(View.GONE);
	    //------Date and Time picker-------
	    Button mPickDate = (Button) findViewById(R.id.pickDate);
	    Button mPickTime = (Button) findViewById(R.id.pickTime); 
	    final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
	    //-------End date and Time picker-----
	    	    
	    final ToggleButton newLocationButton = (ToggleButton) findViewById(R.id.newLocButton);
	    final ToggleButton SubmittedBeforeButton = (ToggleButton) findViewById(R.id.sumbBeforeButton);
	    final TextView finalResults = (TextView) findViewById(R.id.textView1d);
	    final TextView submittedBeforeText = (TextView) findViewById(R.id.textView1ac);
	    final TextView completitionStatus = (TextView) findViewById(R.id.textView2);
	    displayTime = (TextView) findViewById(R.id.timeDisplay);
	    displayDate = (TextView) findViewById(R.id.dateDisplay);
	    displayDate2 = (TextView) findViewById(R.id.dateDisplay2);
		final EditText generalComments = (EditText) findViewById(R.id.generalCommentText);
	    final Context context = getApplicationContext();
	    final SharedPreferences pref = getSharedPreferences("AppSettings",MODE_PRIVATE);
	    final EditText treeComments = (EditText) findViewById(R.id.treeComments);
	    
	  	    
	    // for the dialog indicating the gps is disabled
	    builder = new AlertDialog.Builder(this);
	    //setup the gps manager
	    myManager = (LocationManager) getSystemService(LOCATION_SERVICE);	
	    geocoder = new Geocoder(getApplicationContext(), Locale.getDefault() );
        
	    
	    //final Observation newObs = new Observation(pref.getString("userEmail", null),idNumberObs);
	    newObs = new Observation(pref.getString("userEmail", null));
	    /*
		 * Please Note!
		 * This question only needs to be asked once and it will
		 * be entered into user Preferences, it is asking if 
		 * a user has submitted data for a different
		 * site before. If a user answers yes, this will
		 * become an auto-complete answer, if a user enters
		 * "NO" then it will re appear until a counter for the
		 * number times a user submits an obs
		 * while selecting "NO" on using them same site
		 * if the counter >= 2 this question will disappear.
		 * 
		 *   -Daniel
		 */
	    if(pref.getBoolean("SubmitDifSiteBefore", false)==true){
	    	SubmittedBeforeButton.setVisibility(View.GONE);
	    	submittedBeforeText.setVisibility(View.GONE);
		}
	    
	    final Spinner numofGraySquirrelsSpinner = (Spinner) findViewById(R.id.numOfGraySpinner);
	    final Spinner numofFoxSquirrelsSpinner = (Spinner) findViewById(R.id.numOfFoxSpinner);
	    String[] numSpinner = new String[10];
	    for(int i = 0; i<10;i++){
	    	numSpinner[i] =""+i;
	    }
		ArrayAdapter<String> numOfSquirrels = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, numSpinner );
		numofGraySquirrelsSpinner.setAdapter(numOfSquirrels);
		numofFoxSquirrelsSpinner.setAdapter(numOfSquirrels);		
		numofGraySquirrelsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        newObs.setNumOfGray((String) parent.getItemAtPosition(pos));
		    }
		    public void onNothingSelected(AdapterView<?> parent) {
		    }
		});
		numofFoxSquirrelsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        newObs.setNumOfFox((String) parent.getItemAtPosition(pos));
		    }
		    public void onNothingSelected(AdapterView<?> parent) {
		    }
		});
	    
		final boolean showLayout1a = pref.getBoolean("OverwriteDateTimeLoc", false);
		if(showLayout1a){
			layout1.setVisibility(View.GONE);
			nextObsButton2.setVisibility(View.GONE);
			layout1a.setVisibility(View.VISIBLE);
			nextObsButton1.setVisibility(View.VISIBLE);
			// display time and date for the user
		    displayTime.setText(newObs.getTime());
		    displayDate.setText(newObs.getDate());
		    displayDate2.setVisibility(View.GONE);
		}
		else{
			nextObsButton1.setVisibility(View.GONE);
			nextObsButton2.setVisibility(View.VISIBLE);
			backObsButton1a.setVisibility(View.INVISIBLE);
			displayDate2.setText(newObs.getDate());
		}

		
		final Spinner settingSpinner = (Spinner) findViewById(R.id.settingSpinner);
	    String[] settingsArr = {"Single-family home", "Apartment Building", "Highrise", "City Park", "Forest/Nature Preserve", 
	    		"Zoo/Arboretum/Botanical Garden", "Commercial Establishment", "School Campus", "Vacant Lot", "Cemetery", "Farmland"};
	    ArrayAdapter<String> settings = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, settingsArr );
	    settingSpinner.setAdapter(settings);
	    settingSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
		    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
		        newObs.setSetting((String) parent.getItemAtPosition(pos));
		    }
		    public void onNothingSelected(AdapterView<?> parent) {
		    }
		});
	    
	    // Create radio groups

	    final RadioGroup nut_Tree_Group = (RadioGroup) findViewById(R.id.nut_Tree_Group);
	    final RadioGroup seed_Tree_Group = (RadioGroup) findViewById(R.id.seed_Tree_Group);
	    final RadioGroup fruit_Tree_Group = (RadioGroup) findViewById(R.id.fruit_Tree_Group);
	    final RadioGroup tiny_Tree_Group = (RadioGroup) findViewById(R.id.tiny_Tree_Group);
	    final RadioGroup cone_Tree_Group = (RadioGroup) findViewById(R.id.cone_Tree_Group);
	    final RadioGroup bird_Feed_Group = (RadioGroup) findViewById(R.id.bird_Feed_Group);
	    final RadioGroup human_Feed_Group = (RadioGroup) findViewById(R.id.human_Feed_Group);
	    final RadioGroup garbage_Feed_Group = (RadioGroup) findViewById(R.id.garbage_Feed_Group);
	    final RadioGroup other_Feed_Group = (RadioGroup) findViewById(R.id.other_Feed_Group);
	    final RadioGroup plant_Feed_Group = (RadioGroup) findViewById(R.id.plant_Feed_Group);
	    final RadioGroup num_Squirrels_Group = (RadioGroup) findViewById(R.id.num_Squirrels_Group);
	    final RadioGroup dog_Group = (RadioGroup) findViewById(R.id.dog_Group);
	    final RadioGroup cat_Group = (RadioGroup) findViewById(R.id.cat_Group);

	    // Create radio group event listeners
	    nut_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setNutTree("" + rb.getText());
	        }
	    });
	    
	    seed_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setSeedTree("" + rb.getText());
	        }
	    });
	    
	    fruit_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setFruitTree("" + rb.getText());
	        }
	    });
	    
	    tiny_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setTinyTree("" + rb.getText());
	        }
	    });
	    
	    cone_Tree_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setConeTree("" + rb.getText());
	        }
	    });
	    
	    bird_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setBirdFeed("" + rb.getText());
	        }
	    });
	    
	    human_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setHumanFeed("" + rb.getText());
	        }
	    });
	    
	    garbage_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setGarbageFeed("" + rb.getText());
	        }
	    });
	    
	    plant_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setPlantFeed("" + rb.getText());
	        }
	    });
	    
	    other_Feed_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setOtherFeed("" + rb.getText());
	        }
	    });
	    num_Squirrels_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setNumOfSqurrelChange("" + rb.getText());
	        }
	    });
	    dog_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setDogs("" + rb.getText());
	        }
	    });
	    cat_Group.setOnCheckedChangeListener(new OnCheckedChangeListener()
	    {
	        public void onCheckedChanged(RadioGroup buttonView, int checkedID)
	        {
	        	RadioButton rb = (RadioButton) findViewById(checkedID);
	            newObs.setCats("" + rb.getText());
	        }
	    });
	  
	    // Create radio button event listeners

	    // Set radio button defaults
	    ((RadioButton) findViewById(R.id.nut_Tree_No)).performClick();
	    ((RadioButton) findViewById(R.id.seed_Tree_No)).performClick();
	    ((RadioButton) findViewById(R.id.fruit_Tree_No)).performClick();
	    ((RadioButton) findViewById(R.id.tiny_Tree_No)).performClick();
	    ((RadioButton) findViewById(R.id.cone_Tree_No)).performClick();
	    ((RadioButton) findViewById(R.id.bird_Feed_Never)).performClick();
	    ((RadioButton) findViewById(R.id.human_Feed_Never)).performClick();
	    ((RadioButton) findViewById(R.id.garbage_Feed_Never)).performClick();
	    ((RadioButton) findViewById(R.id.plant_Feed_Never)).performClick();
	    ((RadioButton) findViewById(R.id.other_Feed_Never)).performClick();
	    ((RadioButton) findViewById(R.id.num_Squirrels_Same)).performClick();
	    ((RadioButton) findViewById(R.id.dog_None)).performClick();
	    ((RadioButton) findViewById(R.id.cat_None)).performClick();
	    
	    infoIconButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent i = new Intent(newObservation.this, infoMenu.class);
		        startActivity(i);
			}	    	
	    });
	    
	    nextObsButton1.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.VISIBLE);
	    		layout2.setVisibility(View.GONE);
	    		layout3.setVisibility(View.GONE);
	    		nextObsButton1.setVisibility(View.GONE);
	    		backObsButton1.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.VISIBLE);
				nextObsButton3.setVisibility(View.GONE);
				ObsSubmitButton.setVisibility(View.GONE);
				if(showLayout1a){
					backObsButton1a.setVisibility(View.VISIBLE);
				}
				else{
					backObsButton1a.setVisibility(View.INVISIBLE);					
				}
				completitionStatus.setText("20% complete");
			}
	    });
	    nextObsButton2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				layout1a.setVisibility(View.GONE);
				layout1.setVisibility(View.GONE);
				layout2.setVisibility(View.VISIBLE);
				layout3.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton3.setVisibility(View.VISIBLE);
				backObsButton1.setVisibility(View.VISIBLE);
				backObsButton2.setVisibility(View.GONE);
				
				backObsButton1a.setVisibility(View.GONE);					
				
				if(newLocationButton.isChecked()){
					newObs.setUsingSameSite("YES");
				}
				else{
					newObs.setUsingSameSite("NO");
				}
				/*
				 * Please Note!
				 * This question only needs to be asked once and it will
				 * be entered into user Preferences, it is asking if 
				 * a user has submitted data for a different
				 * site before. If a user answers yes, this will
				 * become an auto-complete answer, if a user enters
				 * "NO" then it will re appear until a counter for the
				 * number times a user submits an obs
				 * while selecting "NO" on using them same site
				 * if the counter >= 2 this question will disappear.
				 * 
				 *   -Daniel
				 */
				if(gpsDisabled){
					String zipCodeS = zipCodeText.getText().toString();
					String regTest="(([0-9][0-9][0-9][0-9][0-9])-([0-9][0-9][0-9][0-9]))";
					Pattern p = Pattern.compile(regTest,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
				    Matcher m = p.matcher(zipCodeS);
				    if (!m.find())
				    {
				    	Toast.makeText(getApplicationContext(),"Please enter a full Zipcode in the form of #####-####",Toast.LENGTH_LONG).show();
				    }
				    else{
				    	newObs.setZip("zipCodeS");
				    }
				}
				if(SubmittedBeforeButton.isChecked()){
					newObs.setUsingDifSite("YES");
				}
				else{
					newObs.setUsingDifSite("NO");
				}
				newObs.setGeneralComments(generalComments.getText().toString());
				completitionStatus.setText("100% complete");
			}
			
	    });
	    backObsButton1a.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		layout1a.setVisibility(View.VISIBLE);
	    		layout1.setVisibility(View.GONE);
	    		layout2.setVisibility(View.GONE);
	    		layout3.setVisibility(View.GONE);
	    		nextObsButton1.setVisibility(View.VISIBLE);
	    		backObsButton1.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton3.setVisibility(View.GONE);
				ObsSubmitButton.setVisibility(View.GONE);
				backObsButton1a.setVisibility(View.INVISIBLE);
				
				
			}
	    });
	    backObsButton1.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.VISIBLE);
	    		layout2.setVisibility(View.GONE);
	    		layout3.setVisibility(View.GONE);
	    		backObsButton1.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.VISIBLE);
				nextObsButton3.setVisibility(View.GONE);
				ObsSubmitButton.setVisibility(View.GONE);
				if(showLayout1a){
					backObsButton1a.setVisibility(View.VISIBLE);
				}
				else{
					backObsButton1a.setVisibility(View.INVISIBLE);					
				}
				
				
			}
	    });
	    nextObsButton3.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
				layout2.setVisibility(View.GONE);
				layout3.setVisibility(View.VISIBLE);
				backObsButton1.setVisibility(View.GONE);
				backObsButton2.setVisibility(View.VISIBLE);
				nextObsButton3.setVisibility(View.GONE);
				ObsSubmitButton.setVisibility(View.VISIBLE);
				newObs.setTreeComments(treeComments.getText().toString());
			}
	    });
	    backObsButton2.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout2.setVisibility(View.VISIBLE);
	    		layout3.setVisibility(View.GONE);
	    		backObsButton1.setVisibility(View.VISIBLE);
	    		backObsButton2.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton3.setVisibility(View.VISIBLE);		
				ObsSubmitButton.setVisibility(View.GONE);
			}
	    });
	    ObsSubmitButton.setOnClickListener(new OnClickListener() {
	    	@Override
	    	public void onClick(View v) {
	    		layout1a.setVisibility(View.GONE);
	    		layout1.setVisibility(View.GONE);
	    		layout2.setVisibility(View.GONE);
	    		layout3.setVisibility(View.GONE);
	    		layout4.setVisibility(View.VISIBLE);
	    		backObsButton1.setVisibility(View.GONE);
	    		backObsButton2.setVisibility(View.GONE);
				nextObsButton2.setVisibility(View.GONE);
				nextObsButton3.setVisibility(View.GONE);
				ObsSubmitButton.setVisibility(View.GONE);
				
				
				SharedPreferences.Editor editor = pref.edit();
				
				//pass what we got at the end of the survey
				newObs.setLatLong(latitude, longitude);
				newObs.setZip(zipCode);
				
				/*
				 * Please Note!
				 * This question only needs to be asked once and it will
				 * be entered into user Preferences, it is asking if 
				 * a user has submitted data for a different
				 * site before. If a user answers yes, this will
				 * become an auto-complete answer, if a user enters
				 * "NO" then it will re appear until a counter for the
				 * number times a user submits an obs
				 * while selecting "NO" on using them same site
				 * if the counter >= 2 this question will disappear.
				 * 
				 *   -Daniel
				 */				
				int diffSiteCount = 0;
				if(pref.getBoolean("SubmitDifSiteBefore", false)==true){
					newObs.setUsingDifSite("YES");
				}
				else{
					//it must be false
					if(newObs.getUsingSameSite().equals("NO")){
						diffSiteCount = pref.getInt("DifSiteCounter", 0);								
						editor.putInt("DifSiteCounter", diffSiteCount+1);
						editor.commit();
						int temp = pref.getInt("DifSiteCounter", 0);
						if(temp>=2){
							Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
							editor.putBoolean("SubmitDifSiteBefore", true);
							editor.commit();
						}
					}
					else{
						//yes, using the same site						
						int temp = pref.getInt("DifSiteCounter", 0);
						if(temp>=2){
							Toast.makeText(context,"Submitted Different Site = true",Toast.LENGTH_LONG).show();
							editor.putBoolean("SubmitDifSiteBefore", true);
							editor.commit();
						}
					}
				}		   
				finalResults.setText(newObs.toString());
				String fName = newObs.getName();
				try{
					OutputStreamWriter out = new OutputStreamWriter(openFileOutput(fName, 0));
					out.write(newObs.toString());
					Log.i(TAG, newObs.toString());
					out.close();
				}
				catch(Throwable t) {
					Toast.makeText(context, "Exception: "+ t.toString(), 5000).show();
				}
			
			}
	    });
	    
	    
	    	 // add a click listener to the button
        mPickDate.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
        		//Toast.makeText(getApplicationContext(), "PickDate!", 5000).show();
            }
        });
	  
        // add a click listener to the button
        mPickTime.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
        		//Toast.makeText(getApplicationContext(), "PickTime!", 5000).show();
            }
        });
	    

	
     }
     	@Override
	protected void onStart(){
		builder.setMessage("Your GPS service is disabled, You will have to enter the f" +
	    		"ull zip code manually. Sorry for this inconvience. If you do not know the zip code " +
	    		"please feel free to click on the info button for help.")
	           .setCancelable(false)
	           .setPositiveButton("Okay", new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	                    
	               }
	     });
		if(gpsDisabled){
			gpsAlert = builder.create();
		}
		super.onStart();
	}
	@Override
	protected void onDestroy() {
		stopListening();
		super.onDestroy();
	}
	
	@Override
	protected void onPause() {
		stopListening();
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		startListening();
		super.onResume();
	}
	
    // updates the date in the TextView
    private void updateDisplayDate() {
    	newObs.setDate(mDay, mMonth, mYear);
    	displayDate.setText(newObs.getDate());

    }
    
    
    private void updateDisplayTime() {
    	newObs.setTime(mHour, mMinute);
    	displayTime.setText(newObs.getTime());               
    }
	
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case TIME_DIALOG_ID:
                return new TimePickerDialog(this,
                        mTimeSetListener, mHour, mMinute, false);
            case DATE_DIALOG_ID:
                return new DatePickerDialog(this,
                            mDateSetListener,
                            mYear, mMonth, mDay);
        }
        return null;
    }

    @Override
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch (id) {
            case TIME_DIALOG_ID:
                ((TimePickerDialog) dialog).updateTime(mHour, mMinute);
                break;
            case DATE_DIALOG_ID:
                ((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
                break;
        }
    }  
    
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    	public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth) {
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                mYear = year;
                mMonth = monthOfYear;
                mDay = dayOfMonth;
                updateDisplayDate();
            }
    };

    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {

            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                mHour = hourOfDay;
                mMinute = minute;
                updateDisplayTime();
            }
        };

	//GPS required methods---
	private void startListening() {
		myManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
	}

	private void stopListening() {
		if (myManager != null)
			myManager.removeUpdates(this);
	}
	@Override
	public void onLocationChanged(Location location) {
		latitude = location.getLatitude();
		longitude = location.getLongitude();
		try{
	        List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
	        zipCode = addresses.get(0).getPostalCode();
	        //tvLocationText.setText(zipCode);
	        }
	        catch(Exception e){
	        	//tvLocationText.setText(e.toString());
	        	Log.e("Geocoder Error:", e.toString());
	        }
		
	}
	@Override
	public void onProviderDisabled(String provider) {
		gpsDisabled = true;
		zipCodeText.setVisibility(View.VISIBLE);
	    zipcodeEmg.setVisibility(View.VISIBLE);
	}

	@Override
	public void onProviderEnabled(String provider) {
		gpsDisabled = false;
		zipCodeText.setVisibility(View.GONE);
	    zipcodeEmg.setVisibility(View.GONE);
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {}
	
	    
}
